import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getTokenKey, getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  let hasToken = ''
  if (getTokenKey()) hasToken = getToken(getTokenKey())
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      store.dispatch('settings/funsSetting', { ...to })
      if (store.state.user.data.id) {
        next()
      } else {
        // 监听页面刷新情况
        store.commit('app/ISMESSAGEBOX', false)
        // 获取用户信息
        store.dispatch('user/getInfo').then(accessRoutes => {
          // 动态添加可访问路由表
          accessRoutes.forEach(row => {
            router.addRoute(row)
          })
          // 获取全局系统配置及数据字典
          store.dispatch('settings/globalSettings').then(() => {
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          })
        }).catch(() => {
          store.dispatch('user/resetToken')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        })
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
